import Footer from '@/components/Footer';
import {
  LockOutlined, SmileOutlined,
  UserOutlined,
} from '@ant-design/icons';
import {
  LoginForm,
  ProFormCheckbox,
  ProFormText,
} from '@ant-design/pro-components';
import {useEmotionCss} from '@ant-design/use-emotion-css';
import {Alert, message, Tabs} from 'antd';
import Settings from '../../../../config/defaultSettings';
import React from 'react';
import {flushSync} from 'react-dom';
import {Col, Row} from 'antd';
import CaptchaImg from "@/pages/User/Login/components/CaptchaImg";
import {getPermCode, login} from "@/services/wms-dev-tool/login";
import {SelectLang} from "@/components/RightContent";
import {FormattedMessage, Helmet, useIntl, useModel, history} from "@umijs/max";
import {useRequest} from "@@/plugin-request";


const Lang = () => {
  const langClassName = useEmotionCss(({token}) => {
    return {
      width: 42,
      height: 42,
      lineHeight: '42px',
      position: 'fixed',
      right: 16,
      borderRadius: token.borderRadius,
      ':hover': {
        backgroundColor: token.colorBgTextHover,
      },
    };
  });

  return (
    <div className={langClassName} data-lang>
      {SelectLang && <SelectLang/>}
    </div>
  );
};

const LoginMessage: React.FC<{
  content: string;
}> = ({content}) => {
  return (
    <Alert
      style={{
        marginBottom: 24,
      }}
      message={content}
      type="error"
      showIcon
    />
  );
};

const Login: React.FC = () => {
  const {setInitialState} = useModel('@@initialState');

  const containerClassName = useEmotionCss(() => {
    return {
      display: 'flex',
      flexDirection: 'column',
      height: '100vh',
      overflow: 'auto',
      backgroundImage:
        "url('https://mdn.alipayobjects.com/yuyan_qk0oxh/afts/img/V-_oS6r-i7wAAAAAAAAAAAAAFl94AQBr')",
      backgroundSize: '100% 100%',
    };
  });

  const intl = useIntl();

  const saveUserInfo = async (userInfo: any, token: string) => {
    localStorage.setItem("token", token)
    localStorage.setItem("userInfo", JSON.stringify(userInfo))
    const permCode = await getPermCode(token)
    localStorage.setItem("permCode", JSON.stringify(permCode))
    flushSync(() => {
      setInitialState((s: any) => ({
        ...s,
        currentUser: userInfo,
        permCode,
        token: token
      }));
    })
  };
  let captchaState: { randCodeImage: string, checkKey: number } = {
    randCodeImage: '',
    checkKey: 0
  }

  const {run: loginRun} = useRequest(login, {
    manual: true,
    onSuccess: async (res) => {
      const defaultLoginSuccessMessage = intl.formatMessage({
        id: 'pages.login.success',
        defaultMessage: '登录成功！',
      });
      message.success(defaultLoginSuccessMessage);
      console.log("login success---------------",res.result)
      await saveUserInfo(res.result, res.result.token);
      /** 此方法会跳转到 redirect 参数所在的位置 */
      const urlParams = new URL(window.location.href).searchParams;
      console.log("urlParams--------------------",urlParams)
      history.replace(urlParams.get('redirect') || '/');
      // window.location.reload()//解决退出登录重新计入后layout发生改变的问题
    }
  })

  const handleSubmit = async (values: API.LoginParams) => {
    try {
      // 登录
      values.remember_me = true
      values.checkKey = captchaState.checkKey
      console.log("loginParams------------>", values)
      loginRun({...values})
    } catch (error) {
      const defaultLoginFailureMessage = intl.formatMessage({
        id: 'pages.login.failure',
        defaultMessage: '登录失败，请重试！',
      });
      console.log(error);
      message.error(defaultLoginFailureMessage);
    }
  };
  //验证码改变监听
  const handleCaptchaStateChange = (newState: any) => {
    captchaState = newState
    console.log("captcha state 发生变化--------------->", captchaState)
  }

  return (
    <div className={containerClassName}>
      <Helmet>
        <title>
          {intl.formatMessage({
            id: 'menu.login',
            defaultMessage: '登录页',
          })}
          - {Settings.title}
        </title>
      </Helmet>
      <Lang/>
      <div
        style={{
          flex: '1',
          padding: '32px 0',
        }}
      >
        <LoginForm
          contentStyle={{
            minWidth: 280,
            maxWidth: '75vw',
          }}
          logo={<img alt="logo" src="/logo.svg"/>}
          title="星闪智能仓储开发工具"
          subTitle={intl.formatMessage({id: 'pages.layouts.userLayout.title'})}
          initialValues={{
            autoLogin: true,
          }}
          onFinish={async (values) => {
            await handleSubmit(values as API.LoginParams);
          }}
        >
          <Tabs
            centered
            items={[
              {
                key: 'account',
                label: intl.formatMessage({
                  id: 'pages.login.accountLogin.tab',
                  defaultMessage: '账户密码登录',
                }),
              }
            ]}
          />

          {status === 'error' && (
            <LoginMessage
              content={intl.formatMessage({
                id: 'pages.login.accountLogin.errorMessage',
                defaultMessage: '账户或密码错误',
              })}
            />
          )}
          {(
            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined/>,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.username.placeholder',
                  defaultMessage: '请输入用户名',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.username.required"
                        defaultMessage="请输入用户名!"
                      />
                    ),
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined/>,
                }}
                placeholder={intl.formatMessage({
                  id: 'pages.login.password.placeholder',
                  defaultMessage: '请输入密码',
                })}
                rules={[
                  {
                    required: true,
                    message: (
                      <FormattedMessage
                        id="pages.login.password.required"
                        defaultMessage="请输入密码！"
                      />
                    ),
                  },
                ]}
              />
              <Row gutter={8}>
                <Col span={16}>
                  <ProFormText
                    name="captcha"
                    fieldProps={{
                      size: 'large',
                      prefix: <SmileOutlined/>,
                      maxLength: 4
                    }}
                    placeholder={intl.formatMessage({
                      id: 'pages.login.captcha.placeholder'
                    })}
                    rules={[
                      {
                        required: true,
                        message: (
                          <FormattedMessage
                            id="pages.login.captcha.required"
                          />
                        ),
                      },
                    ]}
                  />
                </Col>
                <Col span={8} style={{marginTop: '2px'}}>
                  <CaptchaImg onStateChange={handleCaptchaStateChange}/>
                </Col>
              </Row>
            </>
          )}
          <div
            style={{
              marginBottom: 24,
            }}
          >
            <ProFormCheckbox noStyle name="autoLogin">
              <FormattedMessage id="pages.login.rememberMe" defaultMessage="自动登录"/>
            </ProFormCheckbox>
            <a
              style={{
                float: 'right',
              }}
            >
            </a>
          </div>
        </LoginForm>
      </div>
      <Footer/>
    </div>
  );
};

export default Login;
